#include "WarGameLib.h"


wgGLShaderProgram::wgGLShaderProgram()
{
	programID = vertexShaderID = fragmentShaderID = 0;

}

wgGLShaderProgram::~wgGLShaderProgram()
{
	if(vertexShaderID!=0)
	{
		glDetachShader(programID, vertexShaderID);
		glDeleteShader(vertexShaderID);
	}
	if(fragmentShaderID !=0)
	{
		glDetachShader(programID, fragmentShaderID);
		glDeleteShader(fragmentShaderID);
	}
	if(programID!=0)
		glDeleteProgram(programID);
}

void wgGLShaderProgram::Create()
{
	programID = glCreateProgram();
	glUseProgram(programID);
}



bool PrintShaderInfoLog(unsigned shaderID)
{
	GLsizei infoLogLength;
	glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH,&infoLogLength);
	if(infoLogLength > 0)
	{
		char *infoLog = new char[infoLogLength];
		glGetShaderInfoLog(shaderID, infoLogLength, 0, infoLog);
		cout << infoLog << endl;
		delete infoLog;
		glDeleteShader(shaderID);
	}


	int err;
	glGetShaderiv(shaderID,GL_COMPILE_STATUS,&err);
	if(!err)
		return false;

	return true;
}

bool wgGLShaderProgram::AddShader(const char *filename, unsigned shaderType)
{

	

	FILE*	file;
	fopen_s(&file, filename, "r");
	if(file == 0)
	{
		cout << "Shader source not found: " << filename << endl;
		return false;
	}
	size_t fileSize;
	fseek (file, 0, SEEK_END);
	fileSize=  ftell(file);
	fseek(file, 0, SEEK_SET);
	char *source = new char[fileSize];
	fread(&source[0], 1, fileSize, file);
	fclose(file);

	for(unsigned i = 0; i < fileSize; ++i)
		if(source[i] < 0)
			source[i] = '\0';
//	MessageBoxA(GetActiveWindow(), source, "Shader Code", MB_OK | MB_ICONINFORMATION);

	
	int shaderID = glCreateShader(shaderType);
	int length = strlen(source);
	const char * sourcePtr = source;
	glShaderSource(shaderID, 1, &sourcePtr, &length);
	

	delete source;
	
	
	
	
	glAttachShader(programID, shaderID);

	glCompileShader(shaderID);
	if(!PrintShaderInfoLog(shaderID))
		return false;

	switch(shaderType)
	{
	case GL_VERTEX_SHADER:
		vertexShaderID = shaderID;break;
	case GL_FRAGMENT_SHADER:
		fragmentShaderID = shaderID;break;
	}
	return true;
}


bool wgGLShaderProgram::Link()
{
	glLinkProgram(programID);

	GLsizei infoLogLength;
	glGetProgramiv(programID, GL_INFO_LOG_LENGTH,&infoLogLength);
	if(infoLogLength > 0)
	{
		char *infoLog = new char[infoLogLength];
		glGetProgramInfoLog(programID, infoLogLength, 0, infoLog);
		cout << infoLog << endl;
		delete infoLog;
		
	}
	int err;
	glGetShaderiv(programID,GL_LINK_STATUS,&err);
	if(err != 0)
		return false;


	glUseProgram(programID);

	return true;
}

bool wgGLShaderProgram::AddVertexShader(const char * filename)
{
	return AddShader(filename, GL_VERTEX_SHADER);
}
bool wgGLShaderProgram::AddFragmentShader(const char * filename)
{
	return AddShader(filename, GL_FRAGMENT_SHADER);
}